"""
EventBus与HookHub集成使用示例
展示如何在实际应用中结合使用两个事件系统
"""

import time
import threading
from event_bus_bridge import EventBusBridge
from hook_hub import HookHub


def camera_frame_handler(**kwargs) -> None:
    """处理相机帧数据"""
    payload = kwargs.get('payload', 'unknown')
    print(f"[Camera] 接收到帧数据: {payload}")


def data_processor(**kwargs) -> None:
    """数据处理器"""
    payload = kwargs.get('payload', 'unknown')
    print(f"[Processor] 处理数据: {payload}")


def logger_handler(**kwargs) -> None:
    """日志记录器"""
    payload = kwargs.get('payload', 'unknown')
    print(f"[Logger] 记录事件: {payload}")


def main():
    # 创建HookHub实例
    hook_hub = HookHub()
    
    # 创建桥接器，使用事件ID到事件名称的映射
    event_mapping = {
        0xC0: "camera_frame",
        0xC1: "data_processed",
        0xC2: "system_log"
    }
    bridge = EventBusBridge(hook_hub, event_id_mapping=event_mapping)
    
    # 注册各种事件处理器（注意事件名称与映射中的名称对应）
    hook_hub.register("camera_frame", camera_frame_handler, priority=10)
    hook_hub.register("data_processed", data_processor, priority=5)
    hook_hub.register("system_log", logger_handler, priority=1)
    
    # 注册一个通用事件处理器来处理未映射的事件
    def generic_handler(**kwargs):
        payload = kwargs.get('payload', 'unknown')
        event_name = kwargs.get('event_name', 'unknown')
        print(f"[Generic] 接收到事件 {event_name}: {payload}")
    
    hook_hub.register("cpp_event_c3", generic_handler, priority=1)
    
    # 动态添加新的事件映射
    bridge.add_event_mapping(0xC3, "custom_event")
    
    def custom_handler(**kwargs):
        payload = kwargs.get('payload', 'unknown')
        print(f"[Custom] 自定义事件: {payload}")
    
    hook_hub.register("custom_event", custom_handler, priority=8)
    
    # 模拟发送一些事件到不同的事件ID
    print("开始发送测试事件...")
    
    # 发送到不同事件ID的事件
    bridge.emit_cpp_event(0xC0, "frame_001")
    time.sleep(0.1)
    
    bridge.emit_cpp_event(0xC1, "data_processed_result_001")
    time.sleep(0.1)
    
    bridge.emit_cpp_event(0xC2, "system_log_message")
    time.sleep(0.1)
    
    bridge.emit_cpp_event(0xC3, "custom_event_data")
    time.sleep(0.1)
    
    # 发送一个未映射的事件ID
    bridge.emit_cpp_event(0xC4, "unmapped_event_data")
    time.sleep(0.1)
    
    # 直接通过HookHub发送事件
    print("\n直接通过HookHub发送事件:")
    hook_hub.emit("camera_frame", payload="direct_frame_001")
    time.sleep(0.1)
    
    hook_hub.emit("data_processed", payload="direct_processed_data")
    time.sleep(0.1)
    
    # 模拟长时间运行
    print("\n模拟应用运行中... (5秒后退出)")
    time.sleep(5)
    
    # 清理资源
    print("关闭桥接器...")
    bridge.shutdown()
    print("示例结束")


if __name__ == "__main__":
    main()